//
//  History.m
//  Dormitory2404
//
//  Created by gleeman.G on 2017/12/25.
//  Copyright © 2017年 Hainan Suyun network technology co. LTD. All rights reserved.
//

#import "History.h"

@implementation History

- (void)encodeWithCoder:(NSCoder *)encoder{
    [encoder encodeObject:self.date forKey:@"date"];
    [encoder encodeObject:self.orderList forKey:@"orderList"];
    [encoder encodeObject:self.projectName forKey:@"projectName"];
    
    [encoder encodeFloat:self.totalPrice forKey:@"totalPrice"];
}


- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self)
    {
        self.date     = [aDecoder decodeObjectForKey:@"date"];
        self.orderList     = [aDecoder decodeObjectForKey:@"orderList"];
        self.projectName     = [aDecoder decodeObjectForKey:@"projectName"];
        self.totalPrice = [aDecoder decodeFloatForKey:@"totalPrice"];
    }
    return self;
}

@end


@implementation HistoryList
// 创建静态对象 防止外部访问
static HistoryList *_instance;

+(instancetype)allocWithZone:(struct _NSZone *)zone
{
    //    @synchronized (self) {
    //        // 为了防止多线程同时访问对象，造成多次分配内存空间，所以要加上线程锁
    //        if (_instance == nil) {
    //            _instance = [super allocWithZone:zone];
    //        }
    //        return _instance;
    //    }
    // 也可以使用一次性代码
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (_instance == nil) {
            _instance = [super allocWithZone:zone];
        }
    });
    return _instance;
}

// 为了使实例易于外界访问 我们一般提供一个类方法
// 类方法命名规范 share类名|default类名|类名
+(instancetype)shareInstance
{
    //return _instance;
    // 最好用self 用Tools他的子类调用时会出现错误
    return [[self alloc]init];
}

// 为了严谨，也要重写copyWithZone 和 mutableCopyWithZone
-(id)copyWithZone:(NSZone *)zone
{
    return _instance;
}

-(id)mutableCopyWithZone:(NSZone *)zone
{
    return _instance;
}

- (void)encodeWithCoder:(NSCoder *)encoder{
    [encoder encodeObject:self.historyList forKey:@"historyList"];
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self)
    {
        self.historyList     = [aDecoder decodeObjectForKey:@"historyList"];
    }
    return self;
}

+ (void)saveHistoryList
{
    NSData *historyList = [NSKeyedArchiver archivedDataWithRootObject:[HistoryList shareInstance]];
    
    [[NSUserDefaults standardUserDefaults] setValue:historyList forKey:@"historyList"];
    
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (void)readHistoryList{
    
    NSData *historyList =[[NSUserDefaults standardUserDefaults] valueForKey:@"historyList"];
    
    [NSKeyedUnarchiver unarchiveObjectWithData:historyList];
    
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (NSMutableArray *)historyList
{
    if (!_historyList) {
       _historyList = [[NSMutableArray alloc]init];
    }
    return _historyList;
}

@end
